package com.example.hospital.patient.wx.api.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.map.MapUtil;
import com.example.hospital.patient.wx.api.common.R;
import com.example.hospital.patient.wx.api.controller.form.LoginOrRegisterForm;
import com.example.hospital.patient.wx.api.controller.form.MockLoginForm;
import com.example.hospital.patient.wx.api.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/loginOrRegister")
    public R loginOrRegister(@RequestBody @Valid LoginOrRegisterForm form) {
        HashMap map = userService.loginOrRegister(form.getCode());
        String msg = MapUtil.getStr(map, "msg");
        Map profile = (Map) map.get("profile");
        Integer id = (Integer) profile.get("id");
        StpUtil.login(id);
        String token = StpUtil.getTokenValue();
        profile.put("token", token);
        return R.ok(msg).put("result", profile);
    }

    @PostMapping("/loginByTel")
    public R loginByTel(@RequestBody @Valid MockLoginForm form) {
        Map map = userService.loginByTel(form.getTel());
        String msg = MapUtil.getStr(map, "msg");
        Map profile = (Map) map.get("profile");
        Integer id = (Integer) profile.get("id");
        StpUtil.login(id);
        String token = StpUtil.getTokenValue();
        profile.put("token", token);
        return R.ok(msg).put("result", profile);
    }

    @GetMapping("/getProfile")
    @SaCheckLogin
    public R getProfile(){
        Integer id = StpUtil.getLoginIdAsInt();
        Map profile = userService.getProfile(id);
        return R.ok().put("result", profile);
    }

    @PutMapping("/profile")
    @SaCheckLogin
    public R putProfile(@RequestBody @Param("data")Map data){
        userService.putProfile(data);
        return R.ok();
    }

    @PostMapping("/uploadPhoto")
    @SaCheckLogin
    public R uploadPhoto(@Param("file") MultipartFile file,  @Param("id") Integer id){
        String filename = userService.uploadPhoto(file,id);
        return R.ok().put("result", filename);
    }

    @GetMapping("/profile")
    @SaCheckLogin
    public R getProfileById(){
        int id = StpUtil.getLoginIdAsInt();
        Map profile = userService.getProfile(id);
        profile.put("id",id);
        return R.ok().put("result", profile);
    }
}
